import { makeAutoObservable } from 'mobx';
import { Function, FunctionFormValues } from './functionTypes';
import { getFunctionList, createFunction, updateFunction, deleteFunction, getFunctionDetail} from '../../../../apis/backhub/function';

class FunctionStore {
  functions: Function[] = [];
  modalVisible = false; // 弹窗显示状态
  editingFunction: Function | undefined = undefined; // 当前编辑的函数，undefined表示新建
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取函数列表
  fetchFunctions = async () => {
    this.loading = true;
    try {
      const response = await getFunctionList();
      this.functions = response?.data?.records;
    } catch (error) {
      console.error('获取函数列表失败:', error);
    } finally {
      this.loading = false;
    }
  };


  //获取模型
  getFunction = async (id: string) => {
    try {
      this.loading = true;
      const response = await getFunctionDetail(id);
      this.editingFunction = (response as any).data;
      return this.editingFunction; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingFunction = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (func: Function) => {
    this.getFunction(func.id);
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingFunction = undefined;
  };

  // 保存函数
  saveFunction = async (values: FunctionFormValues) => {
    try {
      if (this.editingFunction && this.editingFunction.id) {
        await updateFunction(this.editingFunction.id, values);
      } else {
        await createFunction(values);
      }
      this.hideModal();
      this.fetchFunctions();
    } catch (error) {
      console.error('保存函数失败:', error);
    }
  };

  // 删除函数
  deleteFunction = async (id: string) => {
    try {
      await deleteFunction(id);
      this.fetchFunctions();
    } catch (error) {
      console.error('删除函数失败:', error);
    }
  };
}

export const functionStore = new FunctionStore();